package com.songcha.sakura.mvvm.local.video

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.sakura.R
import com.songcha.sakura.databinding.FragmentLocalVideoBinding
import com.songcha.sakura.event.DownloadTaskEvent
import com.songcha.sakura.event.DownloadTaskEventType
import com.songcha.sakura.struct.M3u8LocalFile
import com.songcha.sakura.ui.adapter.LocalDownloadAdapter
import com.songcha.sakura.ui.adapter.LocalVideoAdapter
import com.songcha.sakura.config.DownloadConfig
import com.songcha.sakura.download.*
import com.songcha.sakura.struct.VideoType
import com.songcha.sakura.util.*
import com.songcha.library_common.ui.dialog.DialogHelper
import com.songcha.library_common.ui.dialog.ListDialog
import com.songcha.sakura.download.base.DownloadTask
import com.songcha.sakura.download.m3u8.M3u8DownloadOption
import com.songcha.sakura.ui.base.BaseComicMvvmFragment
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class LocalVideoFragment: BaseComicMvvmFragment<LocalVideoViewModel, FragmentLocalVideoBinding>() ,
    LocalVideoAdapter.IOnLocalVideoListener {
    companion object{
        val TAG:String= LocalVideoFragment::class.java.simpleName
    }

    private var mMyServer: com.songcha.sakura.server.MyServer?=null
    private var mAdapter:LocalDownloadAdapter?=null
    //var mFileList: MutableList<M3u8LocalFile> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    override fun isNeedShowLoadingDialog(): Boolean {
        return true
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_local_video
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        setLoadingDialogCancelable(false)

        databinding.rcvDownload.apply {
            layoutManager= LinearLayoutManager(this@LocalVideoFragment.requireContext())
            mAdapter=LocalDownloadAdapter(context, R.layout.item_local_download, viewModel.fileList.value!!,this@LocalVideoFragment)
            mAdapter!!.setOnItemChildClickListener { a, v, p ->
                when(v.id){
                    //R.id.btn_play_video->playVideo(mFileList[p])
                    //R.id.btn_delete_video->deleteVideo(mFileList[p])
                }
            }
            adapter = mAdapter

        }

        viewModel.fileList.observe(viewLifecycleOwner){
            mAdapter?.notifyDataSetChanged()
        }
        viewModel.isConverting.observe(viewLifecycleOwner){
            if(it){
                showLoadingDialog(true)
            }else{
                hideLoadingDialog()
                viewModel.getLocalVideoList(requireContext())
            }
        }

        viewModel.isCopying.observe(viewLifecycleOwner){
            if(it){
                showLoadingDialog(true)
            }else{
                hideLoadingDialog()
            }
        }

        /*viewModel.isGetingLocalFile.observe(viewLifecycleOwner){
            if(it){
                viewModel.onLoading()
            }else{
            }
        }*/
    }



    private fun playVideo(video: M3u8LocalFile.LocalVideo){
        if(video.type!=VideoType.M3U8){
            MyJumpUtil.toVideo(requireContext(),video.absoluteEpisodePath,video.episodeName, isLocal = true)
        }else{
            try {
                if(mMyServer==null)
                    mMyServer = com.songcha.sakura.server.MyServer(8080)
                mMyServer!!.stop()
                mMyServer!!.start()
                val url="http://127.0.0.1:8080"+ DownloadConfig.getVideoDownloadPath()+"/"+video.title+"/"+video.episodePath.substring(0,video.episodePath.length-2)
                //val url="http://127.0.0.1:8080"+requireContext().filesDir.absolutePath+"/"+video.title+"/"+video.episodePath.substring(1,video.episodePath.length-2)
                LogUtil.log("本地播放",url)
                MyJumpUtil.toVideo(requireContext(),url,video.episodeName, isLocal = true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }


    override fun onAppBackGround() {
        super.onAppBackGround()
        mMyServer?.stop()
    }

    private fun showVideoOpDialog(video: M3u8LocalFile.LocalVideo){
        var list= mutableListOf("删除")
        if(video.type==VideoType.M3U8){
            list.add("转成mp4")
        }else{
            //list.add("复制到沙盒目录")
        }

        val dialog=ListDialog(requireContext(),list)
        dialog.apply {
            setDialogTitle("选择操作")
            setOnListDialogItemClickListener{p->
                when(p){
                    0->{
                        viewModel.deleteVideo(video)
                        ToastUtil.show("删除成功")
                        if(video.type==VideoType.M3U8){
                            DownloadServiceController.cancelTask(video.url)
                        }
                        viewModel.getLocalVideoList(requireContext())
                    }
                    1->{
                        if(video.type==VideoType.M3U8){
                            viewModel.ts2Mp4(video)
                        }

                    }
                }
                return@setOnListDialogItemClickListener true
            }
        }
        dialog.show()

        /*DialogHelper.showListDialog(requireContext(),"选择操作",list){ p->
            when(p){
                0->{
                    viewModel.deleteVideo(video)
                    ToastUtil.show("删除成功")
                    if(video.type==VideoType.M3U8){
                        DownloadServiceController.cancelTask(video.url)
                    }
                    viewModel.getLocalVideoList(requireContext())
                }
                1->{
                    if(video.type==VideoType.M3U8){
                        viewModel.ts2Mp4(video)
                    }else{

                    }

                }
            }
            return@showListDialog true
        }*/
    }

   /* fun showLoadingDialog(){
        mLoadingDialog=LoadingDialog(requireContext())
        mLoadingDialog!!.setCancelable(false)
        mLoadingDialog!!.show()
    }

    fun hideLoadingDialog(){
        mLoadingDialog?.dismiss()
    }*/


    /*private fun deleteVideo(video: M3u8LocalFile.LocalVideo){
        val db=CustomDialog.Companion.Builder(requireContext())
            .setTitle("提示")
            .setMsg("是否删除该视频——${video.episodeName}?")
            .setOnConfirmListener {




            }

        db.setWidth(ScreenUtil.getScreenWidth(requireContext()))
            .setGravity(Gravity.BOTTOM)
            .setAnim(R.style.dialogBottomSlideWindowAnim)
            .create()
            .show()

    }*/


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        ProcessLifecycleOwner.get().lifecycle.removeObserver(this)
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
        viewModel.getLocalVideoList(requireContext())
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    fun onDownloadTaskChange(event: DownloadTaskEvent) {
        //LogUtil.log("aaa",event.type)
        when(event.type){
            DownloadTaskEventType.PRE->{

            }
            DownloadTaskEventType.INITIALIZE->{

            }
            DownloadTaskEventType.START->{
                viewModel.getLocalVideoList(requireContext())
            }
            DownloadTaskEventType.UPDATE->{
                event.task?.let {
                    updateLocalVideo(it)
                }
            }
            DownloadTaskEventType.COMPLETED->{
                viewModel.getLocalVideoList(requireContext())
                //binding.btnDownload.text=event.task?.percent.toString()
            }
            else -> {}
        }
    }


    fun updateLocalVideo(task: DownloadTask){
        val fileList= viewModel.fileList.value ?:return
        task.option as M3u8DownloadOption
        for(i in fileList.indices){
            for(j in fileList[i].list.indices){
                if(fileList[i].list[j].absoluteEpisodePath==task.option.episodePath){
                    fileList[i].list[j].fileSize=task.currentSize
                    mAdapter?.updateVideoCurrentSize(i,j)
                    break
                }
            }
        }
    }

    override fun onPlayVideo(video: M3u8LocalFile.LocalVideo) {
        playVideo(video)
    }

    override fun onDeleteVideo(video: M3u8LocalFile.LocalVideo) {
        //deleteVideo(video)
        showVideoOpDialog(video)
    }


}